// pages/repair/repair.js
import api from "../../Sendingmethod/Sendingmethod"
import {
    Bseurl
} from "../../baseurl/baseurl"
import
encrypt
from "../../utils/crypto-util.js"
import util from '../../utils/util'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        showon: false,
        actions: [{
                name: '设备报修',
                kephone: 1
            },
            {
                name: '设备报废',
                kephone: 2
            },
        ],
        bxname: '选择报修类型',
        bxtype: '',
        tailsimg: "",
        emid: "",
        emdata: {},
        fromdata: {
            type: "",
            describe: "",
            image: ""
        },
        feikomh: false
    },

    /**
     * 图片上传
     */
    updateimg(e) {
        let _that = this
        console.log(e.target.dataset.type);
        wx.chooseMedia({
            count: 1, // 可选择的图片数量
            mediaType: ['image'],
            sizeType: ['compressed'], // 压缩图片
            sourceType: ['album', 'camera'], // 来源：相册或相机
            success: (res) => {
                console.log(res, '上传图片');
                this.imgeuplode(res.tempFiles[0].tempFilePath)
            }
        })
    },
    getUuid() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = (Math.random() * 16) | 0,
                v = c == 'x' ? r : (r & 0x3) | 0x8;
            return v.toString(16);
        });
    },
    /**
     * 上传函数
     */
    imgeuplode(data) {
        wx.showLoading({
            mask: true
        })
        // 获取当前时间戳
        let datatime = new Date().getTime()
        console.log(data);
        let Randomnum = this.getUuid()
        let aecdata
        let md5
        let _that = this
        md5 = encrypt.md5(`sign:data=&nonceStr=${Randomnum}&timestamp=${datatime}`)
        wx.uploadFile({
            url: 'https://api.business.dayenginer.com/user/attachment',
            filePath: data,
            formData: {},
            name: 'file',
            header: {
                "h_uid": wx.getStorageSync('userid') ? wx.getStorageSync('userid') : '',
                "h_timestamp": datatime,
                "h_nonceStr": Randomnum,
                "h_sign": md5,
                "h_token": wx.getStorageSync('token') ? wx.getStorageSync('token') : '',
                "h_deviceId": '',
                'Content-Type': 'multipart/form-data'
            },
            success(res) {
                console.log(res, "上传成功");
                let resone = JSON.parse(encrypt.aesDecrypt(res.data))
                console.log(resone, '上传返回值');
                wx.hideLoading()
                //判断
                if (resone.code == 0) {
                    _that.setData({
                        ['fromdata.image']: resone.data.url
                    })
                }



                _that.feikkong()
            },
            fail(res) {
                console.log(res, '上传失败');
                console.log(JSON.parse(encrypt.aesDecrypt(res.data)));
                wx.hideLoading()
            }
        })
    },
    /**
     * 输入事件
     */
    shurushijian(e) {
        console.log(e);
        this.setData({
            ['fromdata.describe']: e.detail.value
        })
        this.feikkong()
    },
    /**
     * 非空判断
     */
    feikkong() {
        const emptyCount = Object.keys(this.data.fromdata).filter(key => this.data.fromdata[key] === "").length;
        console.log(emptyCount);
        if (emptyCount > 0) {
            console.log(this.data.fromdata, '未通过');
            this.setData({
                feikomh: false
            })
        } else {
            console.log(this.data.fromdata, '已通过');
            this.setData({
                feikomh: true
            })
        }
    },
    /**
     * 报修上传
     */
    async baoxiuupdate() {
        wx.showLoading({
            mask: true
        })
        console.log('测试成功');
        try {
            let res = await api.emrepair({
                ...this.data.fromdata,
                device_id: this.data.emid
            })
            console.log(res);
            if (res.code == 0) {
                wx.hideLoading()
                wx.showToast({
                    title: res.msg,
                    icon: 'success',
                    duration: 2000
                })
                wx.navigateBack(1)
            } else {
                wx.hideLoading()
                wx.showToast({
                    title: res.msg,
                    icon: 'error',
                    duration: 2000
                })
            }
        } catch (error) {
            console.error(error);
            wx.hideLoading()
            wx.showToast({
                title: res.msg,
                icon: 'error',
                duration: 2000
            })
        }
    },
    tijiaofagdu: util.throttle(function () {
        this.baoxiuupdate()
    },1000),

    goto() {
        wx.navigateTo({
            url: `/pages/Repair_Record/Repair_Record?emid=${this.data.emid}`,
        })
    },
    onCancel() {
        this.setData({
            showon: !this.data.showon
        });

    },
    btntab(e) {
        console.log(e.detail);
        console.log(e.detail.name);

        this.setData({
            showon: false,
            bxname: e.detail.name,
            ['fromdata.type']: e.detail.kephone,
        });
        this.feikkong()

    },
    openbox() {
        this.setData({
            showon: true
        })
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log(options, '传值');
        if (options.emid) {
            this.setData({
                emid: options.emid
            })
        }

    },
    /**
     * 获取详细信息
     */
    async geiinfo() {

        try {
            let res = await api.devicedetail({
                id: this.data.emid
            })
            console.log(res, '详细信息');
            if (res.code == 0) {
                this.setData({
                    emdata: res.data
                })
            } else {

            }

        } catch (error) {
            console.error(error, '请求错误');
        }

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.geiinfo()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})